﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;

namespace Bangle.JSONHelpter
{
    public class DateTimeJavaScriptConverter : JavaScriptConverter{

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            long ticks = (long)dictionary["Ticks"];
            return new DateTime(ticks);
        }
         
        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            IDictionary<string, object> result = new Dictionary<string, object>();
            if (obj is DateTime)
            {
                DateTime dt = (DateTime)obj;

                long tik = Decimal.ToInt64(Decimal.Divide(dt.Ticks - new DateTime(1970, 1, 1, 8, 0, 0).Ticks, 10000));
                result.Add("Ticks", tik);
            }
            return result;
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get {
                List<Type> types = new List<Type>();
                types.Add(typeof(DateTime));
                return types;
                }
        }
    }

   public class JSON
    {
        public static T parse<T>(string jsonString)
        {
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }

        //public static string stringify(object jsonObject)
        //{
        //    using (var ms = new MemoryStream())
        //    {
        //        new DataContractJsonSerializer(jsonObject.GetType()).WriteObject(ms, jsonObject);
        //        return Encoding.UTF8.GetString(ms.ToArray());
        //    }
        //}

        public static string stringify(object jsonObject)
        { 
         JavaScriptSerializer js =new JavaScriptSerializer();


         DateTimeJavaScriptConverter dtjc = new DateTimeJavaScriptConverter();

         List<JavaScriptConverter> dtjs = new List<JavaScriptConverter>();
         dtjs.Add(dtjc);
         js.RegisterConverters(dtjs);
          
          return js.Serialize(jsonObject);
                
        }
       
    }
}
